package com.applet.interceptor;

import com.alibaba.fastjson.JSON;
import com.applet.common.constant.ResultConstant;
import com.applet.common.context.BaseContext;
import com.applet.common.exection.InsufficientPermissionsException;
import com.applet.common.vo.Result;
import com.applet.pojo.entity.User;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author “XuShao”
 * @date 2024/12/19 16:38
 * @description 权限拦截器
 */
//@Component
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        log.info("拦截管理端，当前用户 => {}-{}", BaseContext.getCurrentId(), BaseContext.getCurrentPerm());

        if(BaseContext.getCurrentPerm() == User.PERM_1) return true;

        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("UTF-8");

        response.getWriter().write(JSON.toJSONString(Result.fail(
                ResultConstant.FAIL_DENIED.getCode(),
                ResultConstant.FAIL_DENIED.getMessage()
        )));

        return true;
    }
}
